'use strict';
(function(){
  // Config + utils
  const $ = (s, c=document) => c.querySelector(s);
  const $$ = (s, c=document) => Array.from(c.querySelectorAll(s));
  const storage = {
    get(k, fb){ try{ return JSON.parse(localStorage.getItem(k) || JSON.stringify(fb)); }catch(e){ return fb; } },
    set(k, v){ localStorage.setItem(k, JSON.stringify(v)); }
  };
  let API_BASE = null, USE_SERVER = false, COMPANY = null;

  async function loadJSON(url){ try{ const r = await fetch(url, {cache:'no-store'}); return r.ok ? await r.json() : null; }catch(e){ return null; } }
  async function initBackend(){
    API_BASE = (await loadJSON('config/api-config.json'))?.apiBase || null;
    COMPANY = await loadJSON('config/company.json');
    if(API_BASE){
      try{ const c = new AbortController(); const t = setTimeout(()=>c.abort(), 1200); const r = await fetch(API_BASE + '/api/health', {signal:c.signal}); clearTimeout(t); USE_SERVER = r.ok; }catch(e){ USE_SERVER = false; }
    }
    if(USE_SERVER){
      const hint = document.createElement('div'); hint.className='muted'; hint.textContent = '已连接服务端：' + API_BASE;
      $('#invoice h4')?.parentElement?.insertBefore(hint, $('#invoice h4').nextSibling);
    }
  }
  async function api(method, path, body){
    if(!USE_SERVER) throw new Error('server-off');
    const res = await fetch(API_BASE + path, { method, headers: {'Content-Type':'application/json'}, body: body ? JSON.stringify(body) : undefined });
    if(!res.ok) throw new Error('HTTP ' + res.status);
    const ct = res.headers.get('Content-Type') || '';
    return ct.includes('application/pdf') ? (await res.arrayBuffer()) : (await res.json());
  }
  function escapeHTML(s){ return String(s||'').replace(/[&<>\"']/g, (c)=>({"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;"}[c])); }
  function addDays(dateStr, days){ const d = dateStr ? new Date(dateStr) : new Date(); d.setDate(d.getDate() + (days||0)); return d.toISOString().slice(0,10); }
  function formatMoney(n){ return (isNaN(n) ? 0 : +n).toFixed(2); }

  // Tabs
  function setupTabs(){
    const tabs = $$('.tabs .tab'); const sections = $$('.section');
    function activate(id){
      tabs.forEach(b => b.setAttribute('aria-selected', String(b.dataset.target === id)));
      sections.forEach(s => { const on = '#' + s.id === id; s.classList.toggle('active', on); on ? s.removeAttribute('hidden') : s.setAttribute('hidden','hidden'); });
      const h = $(id + ' h4, ' + id + ' h3'); if(h){ h.setAttribute('tabindex','-1'); h.focus({preventScroll:true}); h.removeAttribute('tabindex'); }
    }
    tabs.forEach(b => b.addEventListener('click', ()=>activate(b.dataset.target)));
    const active = $('.section.active'); if(active){ sections.forEach(s => s.id === active.id ? s.removeAttribute('hidden') : s.setAttribute('hidden','hidden')); }
    window.__activateTab = activate;
  }

  // Headers
  const KEY_HEADERS = 'rt_invoice_headers';
  function localHeaders(){ return storage.get(KEY_HEADERS, []); }
  function saveLocalHeaders(list){ storage.set(KEY_HEADERS, list); }
  async function loadHeaders(){ if(USE_SERVER){ try{ return await api('GET','/api/headers'); }catch(e){} } return localHeaders(); }
  async function persistHeader(item, method){
    if(USE_SERVER){
      if(method==='DELETE') return api('DELETE','/api/headers/'+encodeURIComponent(item.id));
      if(method==='POST') return api('POST','/api/headers', item);
      if(method==='PUT') return api('PUT','/api/headers/'+encodeURIComponent(item.id), item);
    }else{
      let list = localHeaders();
      if(method==='DELETE'){ list = list.filter(h=>h.id!==item.id); }
      else{ if(item.default) list = list.map(h=>({...h, default:false})); const i=list.findIndex(h=>h.id===item.id); (i>=0)?(list[i]=item):(list.push(item)); }
      saveLocalHeaders(list); return item;
    }
  }
  function genId(p='H'){ return p + Math.random().toString(36).slice(2,10); }
  async function renderHeaderList(){
    const list = await loadHeaders(); const tbody = $('#header-list tbody'); if(!tbody) return; tbody.innerHTML='';
    list.forEach(h => { const tr = document.createElement('tr'); tr.innerHTML = `<td>${escapeHTML(h.title||'')}</td><td>${escapeHTML(h.taxId||'')}</td><td>${h.default?'✅':''}</td><td><button class="btn small" data-act="edit" data-id="${h.id}">编辑</button></td>`; tbody.appendChild(tr); });
    tbody.onclick = async (e)=>{ const btn = e.target.closest('button[data-act="edit"]'); if(!btn) return; const id=btn.dataset.id; const h=(await loadHeaders()).find(x=>x.id===id); if(h) fillHeaderForm(h); window.__activateTab && window.__activateTab('#invoice'); setTimeout(()=>$('#header-form')?.scrollIntoView({behavior:'smooth'}),50); };
    await populateHeaderSelect();
  }
  async function populateHeaderSelect(){
    const sel = $('#inv-header-select'); if(!sel) return; const headers = await loadHeaders(); sel.innerHTML='';
    const empty = document.createElement('option'); empty.value=''; empty.textContent='— 请选择抬头 —'; sel.appendChild(empty);
    headers.forEach(h => { const o=document.createElement('option'); o.value=h.id; o.textContent=h.title+(h.default?'（默认）':''); sel.appendChild(o); });
    const dft = headers.find(h=>h.default); if(dft) sel.value=dft.id;
  }
  function fillHeaderForm(h){ $('#header-id').value=h?.id||''; $('#header-title').value=h?.title||''; $('#header-taxid').value=h?.taxId||''; $('#header-address').value=h?.address||''; $('#header-phone').value=h?.phone||''; $('#header-bank').value=h?.bank||''; $('#header-account').value=h?.account||''; $('#header-email').value=h?.email||''; $('#header-default').checked=!!h?.default; $('#header-delete').disabled=!h?.id; }
  function resetHeaderForm(){ fillHeaderForm({}); }
  function bindHeaderForm(){
    $('#header-form')?.addEventListener('submit', async (e)=>{
      e.preventDefault();
      const id = $('#header-id').value || genId('H');
      const item = { id, title:$('#header-title').value.trim(), taxId:$('#header-taxid').value.trim(), address:$('#header-address').value.trim(), phone:$('#header-phone').value.trim(), bank:$('#header-bank').value.trim(), account:$('#header-account').value.trim(), email:$('#header-email').value.trim(), default:$('#header-default').checked };
      if(!item.title || !item.taxId){ alert('请填写必填字段：抬头名称与纳税人识别号'); return; }
      await persistHeader(item, $('#header-id').value ? 'PUT' : 'POST'); await renderHeaderList(); alert('已保存抬头'); resetHeaderForm();
    });
    $('#header-reset')?.addEventListener('click', resetHeaderForm);
    $('#header-delete')?.addEventListener('click', async ()=>{ const id=$('#header-id').value; if(!id) return; if(!confirm('确定删除该抬头？')) return; await persistHeader({id}, 'DELETE'); await renderHeaderList(); resetHeaderForm(); });
    $('#open-header-manager')?.addEventListener('click', ()=>{ window.__activateTab && window.__activateTab('#invoice'); setTimeout(()=>$('#header-form')?.scrollIntoView({behavior:'smooth'}),50); });
    $('#go-manage-headers')?.addEventListener('click', ()=>{ window.__activateTab && window.__activateTab('#invoice'); setTimeout(()=>$('#header-form')?.scrollIntoView({behavior:'smooth'}),50); });
  }

  // Invoice
  function getItems(){
    return $$('#inv-items-table tbody tr').map(tr=>{
      const desc = $('input[data-field="desc"]', tr).value.trim();
      const qty = parseFloat($('input[data-field="qty"]', tr).value)||0;
      const price = parseFloat($('input[data-field="price"]', tr).value)||0;
      return {desc, qty, price, amount: qty*price};
    }).filter(x=>x.desc);
  }
  function addItemRow(d={desc:'', qty:1, price:0}){
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td><input data-field="desc" type="text" placeholder="如：音乐版权使用费 / 订单#1234" value="${escapeHTML(d.desc)}"/></td>
      <td><input data-field="qty" type="number" min="0" step="1" value="${d.qty}"/></td>
      <td><input data-field="price" type="number" min="0" step="0.01" value="${d.price}"/></td>
      <td class="ta-right" data-field="vat">0.00</td>
      <td class="ta-right" data-field="amount">0.00</td>
      <td><button class="btn small danger" data-act="del" type="button">删除</button></td>`;
    $('#inv-items-table tbody').appendChild(tr);
    const recalc=()=>computeTotals(); ['qty','price','desc'].forEach(k=>$('input[data-field="'+k+'"]', tr).addEventListener('input', recalc));
    tr.addEventListener('click', e=>{ if(e.target.closest('button[data-act="del"]')){ tr.remove(); computeTotals(); }});
    computeTotals();
  }
  function computeTotals(){
    const items = getItems(); let subtotal=0;
    items.forEach((it,i)=>{subtotal += it.amount; const row=$('#inv-items-table tbody tr:nth-child('+(i+1)+')'); if(row){ const vatAmt = it.amount*(parseFloat($('#inv-tax-rate').value)||0); $('td[data-field="vat"]', row).textContent = formatMoney(vatAmt); $('td[data-field="amount"]', row).textContent = formatMoney(it.amount); }});
    const taxRate = parseFloat($('#inv-tax-rate').value)||0; const tax=subtotal*taxRate; const total=subtotal+tax;
    $('#inv-subtotal').textContent=formatMoney(subtotal); $('#inv-tax').textContent=formatMoney(tax); $('#inv-total').textContent=formatMoney(total);
    // terms → due
    const created = new Date().toISOString().slice(0,10); const terms=$('#inv-terms')?.value||'receipt'; const days= terms==='net20'?20 : terms==='net30'?30 : 0;
    $('#inv-created-date') && ($('#inv-created-date').textContent = created);
    $('#inv-due-date') && ($('#inv-due-date').textContent = addDays(created, days));
  }
  function invoiceNo(){ const d=new Date(); const pad=(n)=>String(n).padStart(2,'0'); const r=Math.random().toString(36).slice(2,6).toUpperCase(); return `INV-${d.getFullYear()}${pad(d.getMonth()+1)}${pad(d.getDate())}-${r}`; }
  function bindInvoice(){
    $('#inv-add-item')?.addEventListener('click', ()=>addItemRow()); addItemRow();
    $('#inv-items-table')?.addEventListener('input', computeTotals); $('#inv-tax-rate')?.addEventListener('input', computeTotals);
    $('#inv-preview')?.addEventListener('click', async ()=>{
      const headers = await loadHeaders(); const id = $('#inv-header-select').value; const h = headers.find(x=>x.id===id);
      if(!h){ alert('请先选择抬头'); return; }
      const items = getItems(); if(items.length===0){ alert('请至少添加一条项目'); return; }
      const currency = $('#inv-currency').value || 'CNY'; const date = new Date().toISOString().slice(0,10); const no = invoiceNo();
      const wrap = $('#inv-preview-wrap'); wrap.style.display='block';
      // buyer
      wrap.querySelector('[data-field="title"]').textContent = h.title||'';
      wrap.querySelector('[data-field="taxId"]').textContent = h.taxId||'';
      wrap.querySelector('[data-field="address"]').textContent = h.address||'';
      wrap.querySelector('[data-field="phone"]').textContent = h.phone||'';
      // seller
      if(COMPANY){
        wrap.querySelector('[data-field="sellerName"]').textContent = COMPANY.companyName||'';
        wrap.querySelector('[data-field="sellerLegal"]').textContent = COMPANY.legalEntity||'';
        wrap.querySelector('[data-field="sellerVAT"]').textContent = COMPANY.vatNo||'';
        wrap.querySelector('[data-field="sellerAddr"]').textContent = COMPANY.address||'';
        wrap.querySelector('[data-field="sellerPhone"]').textContent = COMPANY.phone||'';
        wrap.querySelector('[data-field="sellerEmail"]').textContent = COMPANY.email||'';
        wrap.querySelector('[data-field="sellerBank"]').textContent = COMPANY.bankName||'';
        wrap.querySelector('[data-field="sellerAccount"]').textContent = COMPANY.bankAccount||'';
      }
      // meta
      const terms = $('#inv-terms')?.value || 'receipt';
      const method = $('#inv-method')?.value || 'card';
      const status = $('#inv-status')?.value || 'paid';
      const dueDays = terms==='net20'?20 : terms==='net30'?30 : 0;
      wrap.querySelector('[data-field="date"]').textContent = date;
      wrap.querySelector('[data-field="no"]').textContent = no;
      wrap.querySelector('[data-field="currency"]').textContent = currency;
      wrap.querySelector('[data-field="terms"]').textContent = (terms==='receipt')?'收到即付':(terms==='net20'?'NET 20':'NET 30');
      wrap.querySelector('[data-field="method"]').textContent = (method==='card')?'银行卡/信用卡':(method==='paypal'?'PayPal':'银行转账');
      wrap.querySelector('[data-field="status"]').textContent = (status==='paid')?'已支付':'待支付';
      wrap.querySelector('[data-field="due"]').textContent = addDays(date, dueDays);

      // items
      const tbody = wrap.querySelector('tbody[data-field="items"]'); tbody.innerHTML='';
      let subtotal=0; const taxRate=parseFloat($('#inv-tax-rate').value)||0;
      items.forEach(it=>{ const tr=document.createElement('tr'); const vat=it.amount*taxRate; tr.innerHTML=`<td>${escapeHTML(it.desc)}</td><td>${it.qty}</td><td>${formatMoney(it.price)}</td><td>${formatMoney(vat)}</td><td>${formatMoney(it.amount)}</td>`; tbody.appendChild(tr); subtotal+=it.amount; });
      const tax=subtotal*taxRate; const total=subtotal+tax;
      wrap.querySelector('[data-field="subtotal"]').textContent = formatMoney(subtotal);
      wrap.querySelector('[data-field="tax"]').textContent = formatMoney(tax);
      wrap.querySelector('[data-field="total"]').textContent = formatMoney(total);

      $('#inv-print').disabled=false; $('#inv-save').disabled=false; $('#inv-download').disabled=!USE_SERVER;
    });
    $('#inv-print')?.addEventListener('click', ()=>window.print());
    $('#inv-save')?.addEventListener('click', async ()=>{
      const headers = await loadHeaders(); const id=$('#inv-header-select').value; const h=headers.find(x=>x.id===id); const items = getItems();
      const inv = {
        no: $('#inv-preview-wrap [data-field="no"]').textContent || invoiceNo(),
        headerId: h?.id, header:h, items, currency: $('#inv-currency').value, taxRate: parseFloat($('#inv-tax-rate').value)||0,
        email: $('#inv-email').value.trim(),
        terms: ($('#inv-terms')?.value || 'receipt'),
        method: ($('#inv-method')?.value || 'card'),
        status: ($('#inv-status')?.value || 'paid'),
        dueDate: document.querySelector('#inv-due-date')?.textContent || '',
        sellerName: (COMPANY && COMPANY.companyName) || 'Ruotong Music',
        sellerVAT: (COMPANY && COMPANY.vatNo) || '',
        sellerAddr: (COMPANY && COMPANY.address) || '',
        sellerPhone: (COMPANY && COMPANY.phone) || '',
        sellerEmail: (COMPANY && COMPANY.email) || '',
        sellerBank: (COMPANY && COMPANY.bankName) || '',
        sellerAccount: (COMPANY && COMPANY.bankAccount) || '',
        invoiceNote: (COMPANY && COMPANY.invoiceNote) || ''
      };
      if(USE_SERVER){
        try{ const res = await api('POST','/api/invoices', inv); alert('发票已保存到服务器：' + res.no); $('#inv-download').dataset.id = res.id; $('#inv-download').disabled=false; return; }
        catch(e){ console.warn('server save failed, fallback to localStorage', e); }
      }
      const list = storage.get('rt_invoices', []); list.push(inv); storage.set('rt_invoices', list); alert('发票已保存（仅保存在本机浏览器）');
    });
    $('#inv-download')?.addEventListener('click', async ()=>{
      const id = $('#inv-download').dataset.id; if(!id){ alert('请先保存发票到服务器'); return; }
      try{ const buf = await api('GET','/api/invoices/'+encodeURIComponent(id)+'.pdf'); const b=new Blob([buf], {type:'application/pdf'}); const u=URL.createObjecturl(b); const a=document.createElement('a'); a.href=u; a.download='invoice-'+id+'.pdf'; a.click(); setTimeout(()=>URL.revokeObjecturl(u), 2000); }catch(e){ alert('下载失败：'+e.message); }
    });
    $('#inv-header-select')?.addEventListener('change', async ()=>{ const list = await loadHeaders(); const h=list.find(x=>x.id===$('#inv-header-select').value); if(h && h.email && !$('#inv-email').value) $('#inv-email').value=h.email; });
  }

  // License
  function licNo(){ const d=new Date(); const pad=(n)=>String(n).padStart(2,'0'); const r=Math.random().toString(36).slice(2,6).toUpperCase(); return `LC-${d.getFullYear()}${pad(d.getMonth()+1)}${pad(d.getDate())}-${r}`; }
  function selected(name){ return Array.from(document.querySelectorAll('input[name="'+name+'"]:checked')).map(x=>x.value); }
  function bindLicense(){
    $('#lic-preview')?.addEventListener('click', ()=>{
      const no = $('#lic-no').value.trim() || licNo();
      const date = $('#lic-date').value || new Date().toISOString().slice(0,10);
      const licensor = $('#lic-licensor').value.trim() || 'Ruotong Music';
      const licensee = $('#lic-licensee').value.trim();
      const contact = $('#lic-contact').value.trim();
      const email = $('#lic-email').value.trim();
      const track = $('#lic-track').value.trim();
      const isrc = $('#lic-isrc').value.trim();
      const order = $('#lic-order').value.trim();
      const dlDate = $('#lic-dl-date').value;
      const licType = $('#lic-type')?.value || 'project';
      const production = $('#lic-production')?.value.trim();
      const mediaTypes = selected('lic-media');
      const platforms = selected('lic-platform');
      const distribution = $('#lic-distribution')?.value === 'paid' ? ('付费投放' + ($('#lic-budget')?.value ? '（预算约 ' + $('#lic-budget').value + ' 万）' : '')) : '自然发布';
      const endProducts = $('#lic-endproduct-count')?.value === 'multiple' ? '多个作品/系列' : '单一作品/系列';
      const territory = $('#lic-territory').value.trim() || '全球';
      const term = $('#lic-term').value.trim() || '永久';
      const notes = $('#lic-notes').value.trim();

      if(!licensee || !track){ alert('请至少填写：被授权方与作品名称'); return; }
      $('#lic-no').value = no; $('#lic-date').value = date;

      const wrap = $('#lic-preview-wrap'); wrap.style.display='block';
      wrap.querySelector('[data-field="no"]').textContent = no;
      wrap.querySelector('[data-field="date"]').textContent = date;
      wrap.querySelector('[data-field="licensor"]').textContent = licensor;
      wrap.querySelector('[data-field="licensee"]').textContent = licensee;
      wrap.querySelector('[data-field="contact"]').textContent = contact;
      wrap.querySelector('[data-field="email"]').textContent = email;
      wrap.querySelector('[data-field="track"]').textContent = track;
      wrap.querySelector('[data-field="isrc"]').textContent = isrc;
      wrap.querySelector('[data-field="order"]').textContent = order;
      wrap.querySelector('[data-field="dlDate"]').textContent = dlDate;
      wrap.querySelector('[data-field="licenseType"]').textContent = licType==='creator'?'创作者订阅（个人）':licType==='pro'?'商业订阅（公司）':licType==='project'?'项目授权':'自定义';
      wrap.querySelector('[data-field="production"]').textContent = production || '';
      wrap.querySelector('[data-field="mediaTypes"]').textContent = mediaTypes.join('、');
      wrap.querySelector('[data-field="platforms"]').textContent = platforms.join('、');
      wrap.querySelector('[data-field="distribution"]').textContent = distribution;
      wrap.querySelector('[data-field="endProducts"]').textContent = endProducts;
      wrap.querySelector('[data-field="territory"]').textContent = territory;
      wrap.querySelector('[data-field="term"]').textContent = term;
      wrap.querySelector('[data-field="notes"]').textContent = notes;
      wrap.querySelector('[data-field="safelisting"]').textContent = ($('#lic-safelisting')?.value || '').trim();

      if(COMPANY){
        wrap.querySelector('[data-field="issuerName"]').textContent = '授权代表';
        wrap.querySelector('[data-field="issuerCompany"]').textContent = COMPANY.companyName || '';
        wrap.querySelector('[data-field="issuerEmail"]').textContent = COMPANY.email || '';
      }
      $('#lic-print').disabled=false;
      $('#lic-download').disabled = !USE_SERVER;
    });

    $('#lic-print')?.addEventListener('click', ()=>window.print());

    // 服务端保存 + 下载
    const saveBtn = document.createElement('button'); saveBtn.className='btn'; saveBtn.type='button'; saveBtn.textContent='保存证书（服务端）'; saveBtn.id='lic-save';
    $('#license-form .row:last-of-type')?.appendChild(saveBtn);
    saveBtn.addEventListener('click', async ()=>{
      if(!USE_SERVER){ alert('未连接服务端，无法保存证书'); return; }
      const payload = {
        no: $('#lic-no').value.trim() || licNo(), date: $('#lic-date').value || new Date().toISOString().slice(0,10),
        licensor: $('#lic-licensor').value.trim() || 'Ruotong Music', licensee: $('#lic-licensee').value.trim(),
        contact: $('#lic-contact').value.trim(), email: $('#lic-email').value.trim(),
        track: $('#lic-track').value.trim(), isrc: $('#lic-isrc').value.trim(), order: $('#lic-order').value.trim(), dlDate: $('#lic-dl-date').value,
        licenseType: $('#lic-type')?.value || 'project', production: $('#lic-production')?.value || '',
        mediaTypes: Array.from(document.querySelectorAll('input[name="lic-media"]:checked')).map(x=>x.value),
        platforms: Array.from(document.querySelectorAll('input[name="lic-platform"]:checked')).map(x=>x.value),
        distribution: $('#lic-distribution')?.value === 'paid' ? ('付费投放' + ($('#lic-budget')?.value ? '（预算约 ' + $('#lic-budget').value + ' 万）' : '')) : '自然发布',
        endProducts: $('#lic-endproduct-count')?.value === 'multiple' ? '多个作品/系列' : '单一作品/系列',
        territory: $('#lic-territory').value.trim() || '全球', term: $('#lic-term').value.trim() || '永久',
        safelisting: ($('#lic-safelisting')?.value || ''), notes: $('#lic-notes').value.trim(), licenseNote: (COMPANY && COMPANY.licenseNote) || ''
      };
      if(!payload.licensee || !payload.track){ alert('请至少填写：被授权方与作品名称'); return; }
      try{ const res = await api('POST','/api/licenses', payload); alert('证书已保存到服务器：' + res.no); $('#lic-download').dataset.id = res.id; $('#lic-download').disabled=false; }catch(e){ alert('保存失败：'+e.message); }
    });

    $('#lic-download')?.addEventListener('click', async ()=>{
      const id=$('#lic-download').dataset.id; if(!id){ alert('请先保存证书到服务器'); return; }
      try{ const buf=await api('GET','/api/licenses/'+encodeURIComponent(id)+'.pdf'); const b=new Blob([buf],{type:'application/pdf'}); const u=URL.createObjecturl(b); const a=document.createElement('a'); a.href=u; a.download='license-'+id+'.pdf'; a.click(); setTimeout(()=>URL.revokeObjecturl(u),2000); }catch(e){ alert('下载失败：'+e.message); }
    });
  }

  async function init(){
    setupTabs();
    await initBackend();
    bindHeaderForm(); await renderHeaderList(); await populateHeaderSelect();
    bindInvoice(); bindLicense();
  }
  document.readyState==='loading' ? document.addEventListener('DOMContentLoaded', init) : init();
})();
